package com.oracle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oracle.mapper.StudentMapper;
import com.oracle.pojo.Admin;
import com.oracle.pojo.LoginForm;
import com.oracle.pojo.Student;
import com.oracle.service.IStudentService;
import com.oracle.util.MD5;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("studentServiceImpl")   // 指定当前实现类的id
@Transactional
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
    @Override
    public Student login(LoginForm loginForm) {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        // 使用studentQueryWrapper设定查询语句的筛选条件，相当于where后面的语句
        // tb_student数据表中的name字段和登录页面对象中的username属性匹配
        studentQueryWrapper.eq("name",loginForm.getUsername());
        // tb_student数据表中的通过MD5加密后的password字段和登录页面对象中的password属性匹配
        // 这里的第二个参数需要使用MD5加密，因为数据库中的password字段存储的是通过MD5加密后的值
        studentQueryWrapper.eq("password", MD5.encrypt(loginForm.getPassword()));
        // 使用MybatisPlus的内置baseMapper调用查询单个方法，查询数据库的Student对象
        Student student = baseMapper.selectOne(studentQueryWrapper);
        // 方法返回Student对象
        return student;
    }

    @Override
    public Student getStudentById(Long userId) {

        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("id",userId);
        return baseMapper.selectOne(studentQueryWrapper);
    }

    @Override
    public IPage<Student> getStudentByConditions(Page<Student> studentPage, String className, String name) {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(className)) {
            studentQueryWrapper.like("clazz_name",className);
        }
        if (!StringUtils.isEmpty(name)) {
            studentQueryWrapper.like("name",name);
        }
        studentQueryWrapper.orderByDesc("id");
        Page<Student> page = baseMapper.selectPage(studentPage, studentQueryWrapper);
        return page;
    }
}
